package com.foryou.system.common.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.springframework.boot.configurationprocessor.json.JSONObject;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by LJX
 * 2017/12/10 0010 下午 9:17
 */
public class JsonUtil {

    public static String toJson(Object object) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setPrettyPrinting();
        Gson gson = gsonBuilder.create();
        return gson.toJson(object);
    }

    public static Map<String, Object> beanToMap(Object obj) throws Exception {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();

        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            if (key.compareToIgnoreCase("class") == 0) {
                continue;
            }
            Method getter = property.getReadMethod();
            Object value = getter != null ? getter.invoke(obj) : null;
            map.put(key, value);
        }

        return map;
    }

    /**
     * 将实体POJO转化为JSON对象 该方法不要用于将List<T>对象转换成json对象
     * 因为如果对象的字段中有java.sql.Date类型的字段的话会报错 如果是单个对象T，是没有问题的
     * 如果需要将List<T>对象转换成json的话，请用objectToJsonStr()方法
     *
     * @param obj
     * @return
     * @throws Exception
     */
    public static <T> JSONObject objectToJson(T obj) throws Exception {
        if (null == obj)
            return new JSONObject();
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writeValueAsString(obj);
        return new JSONObject(jsonStr);
    }

    /**
     * json转list集合
     * @param json
     * @param <T>
     * @return
     */
    public static <T> List<T> jsonToList (String json) {
        Gson gson = new Gson();
        return gson.fromJson(json, new TypeToken<List<T>>(){}.getType());
    }

    /**
     * list转json字符串
     * @param list
     * @param <T>
     * @return
     */
    public static <T> String listToJson(List<T> list) {
        Gson gson = new Gson();
        String json = gson.toJson(list);
        return json;
    }

    public static Map<String,Object> jsonToMap(String json) {
        Gson gson = new Gson();
        Map<String, Object> maps = gson.fromJson(json, new TypeToken<Map<String, Object>>(){}.getType());
        for (Map.Entry<String, Object> entry : maps.entrySet()) {
            System.out.println("key: " + entry.getKey() + "  " + "value: " + entry.getValue());
        }
        return maps;
    }

}
